<template>
	<view class="container">
			
		<view v-if="loading" style="margin-top: 50%;"><tui-loadmore :index="3" type="primary"></tui-loadmore></view>
		
		<view v-else>
			<tui-loading v-if="submit_loading"></tui-loading>
			<!-- 个人统计 -->
			<tui-grid>
				<block v-for="(item,index) in dataList" :key="index">
					<tui-grid-item :cell="4">
						<text class="tui-grid-label" style="font-weight: bold;">{{ item.number }}</text>
						<text class="tui-grid-label">{{ item.name }}</text>
					</tui-grid-item>
				</block>
			</tui-grid>
			
			<!-- 个人操作 -->
			<view>
				<tui-tabs :tabs="navbar" :bold="true" :currentTab="currentTab" @change="change" disabled></tui-tabs>
				
				<view v-if="navbar[currentTab].ddine_button_show && navbar[currentTab].day_ddine">
					<view v-if="navbar[currentTab].order_cancel_note === true" class="tui-date">明日订餐截至时间，今日 18:00</view>
					
					<!-- 二维码 -->
					<view class="my-canvas">
						<canvas
							:style="{ width: qrcode_w + 'px', height: qrcode_w + 'px' }"
							:canvas-id="'couponQrcode'"
							:id="'couponQrcode'"
						></canvas>
					</view>
					
					<!-- 用餐文字提示 -->
					<view class="tui-ddine-date" style="margin: 0px 0px 20px 0px;">{{ navbar[currentTab].to_day }} {{ ddine_note }}</view>
				</view>
				
				<view v-else>
					<view class="tui-date">{{ navbar[currentTab].date }}</view>
					<view v-if="navbar[currentTab].order_cancel_note === true" class="tui-date">明日订餐截至时间，今日 18:00</view>
				</view>
				
				<view v-if="navbar[currentTab].is_stop_eating === false" class="tui-number">
					<tui-numberbox :iconSize="52" :height="200" :width="380" :size="150" backgroundColor="#fff" color="#333" iconBgColor="rgb(86, 119, 252)" iconColor="#fff" radius="12rpx" :value="navbar[currentTab].num" @change="changeCurrentTabNumber" :disabled="navbar[currentTab].order_cancel"></tui-numberbox>
					
					
					<view v-if="navbar[currentTab].order_cancel === false" class="tui-btn-box">
						<tui-button v-if="navbar[currentTab].num > 0" type="green" @click="numberOrder('cancelOrder')">按数量【退】餐</tui-button>
					</view>
					
					
					<view v-if="navbar[currentTab].order_cancel === false" class="tui-btn-box">
						<tui-button @click="numberOrder('reserveOrder')">按数量【订】餐</tui-button>
					</view>
					
				
				</view>
				<view v-else style="margin-top: 50%;">
					<tui-no-data :fixed="false" imgUrl="/static/images/toast/img_nodata.png">{{ footer_note }}</tui-no-data>
					<view class="footer_note_class">{{ footer_note_sub }}</view>
				</view>
			</view>
			
			
			<!-- 操作菜单 -->
			<tui-actionsheet
			 :zIndex="99999"
			 :show="showActionSheet" 
			 :item-list="itemList" 
			 @click="itemClick"
			 @cancel="closeActionSheet">
			</tui-actionsheet>
			
			<!-- 悬浮按钮 -->
			<tui-fab v-if="dineAdminShow" :btnList="btnList" :maskClosable="true" :zIndex="99999" @click="btnClick"></tui-fab>
		</view>
		
		<!-- 页脚 -->
		<tui-footer :fixed="true" :copyright="footerName"></tui-footer>
			
		<!-- 操作后提示 -->
		<tui-toast ref="toast"></tui-toast>
	</view>
</template>

<script>

	import { Login } from "@/utils/login.js"
	import qrCode from '@/libs/weapp-qrcode.js';
	import { getUserUineData, getAccessToken, getUserDetailInfo, ddineMeal } from "@/api/base.js"
	import * as setting from '@/config/setting.js'
	
	export default {
		data() {
			return {
				footer_note: setting.footerNote,
				footer_note_sub: setting.footerNoteSub,
				ddine_note: '扫码取餐',
				dineAdminShow: false,	// 漂浮按钮的显示
				loading: true,
				submit_loading: false,
				footerName: setting.footerName,
				showActionSheet: false,	// 操作菜单的显示
				itemList: [{text: "确定", color: "#2B2B2B", type: ""}], // 菜单按钮数组
				currentTab: 0,	// 当前标签页
				// 主入口数据
				navbar: [],
				dataList: [],
				// 悬浮按钮数据
				btnList:[{
					color: "#fff",
					text: "刷新",
					pages: ""
				}, {
					color: "#fff",
					text: "设置",
					pages: "/pages/common/setting/setting"
				}, {
					color: "#fff",
					text: "订餐量",
					pages: "/pages/common/statistics/statistics"
				}],
				// 二维码
				qrcode_w: uni.upx2px(480),
			};
		},
		onLoad() {
			Login()
		},
		mounted() {
			var _this = this
			_this.loading = true
			
			setTimeout(function() {
				_this.getApiData()
			}, 500);
			
		},
		watch: {
		    'navbar': {
		        deep: true,
		        handler(val) {
		            this.$nextTick(() => {
		                if (this.navbar[this.currentTab]?.ddine_button_show && this.navbar[this.currentTab]?.day_ddine) {
		                    this.initQrCode();
		                }
		            });
		        }
		    }
		},
		methods: {
			initQrCode() {
				try {
					new qrCode('couponQrcode', {
						text: uni.getStorageSync(setting.userInfo).userid, // 这里应该是动态数据
						width: this.qrcode_w,
						height: this.qrcode_w,
						colorDark: '#333333',
						colorLight: '#FFFFFF',
						correctLevel: qrCode.CorrectLevel.H
					});
					console.log('二维码初始化成功');
				} catch (e) {
					console.error('二维码初始化失败:', e);
				}
			},
			// 从缓存提取用户角色等信息
			getdingdingUserDetailInfo() {
				var _this = this
				getUserDetailInfo().then(res => {
					uni.setStorageSync(setting.userDetailInfo, res.data)
					try {
						 res.data.roles.forEach(function(value){
							 if (value.id == setting.dineId || value.name == setting.dineAdmin) {
								 _this.dineAdminShow = true
							 }
						 })
					} catch (err) {
						console.log('用户角色异常', err)
						_this.dineAdminShow = false
					}
				})
			},
			// 数据请求
			getApiData() {
				getUserUineData({ userid: uni.getStorageSync(setting.userInfo).userid }).then(res => {
					this.navbar = res.data.navbars
					this.dataList = res.data.dataLists
					console.log('请求自有后端接口数据', res)
					// 获取用户详细x信息(角色用于判断是否显示悬浮按钮)
					getAccessToken().then(resA => {
						uni.setStorageSync(setting.accessToken, resA.data.access_token)
						this.getdingdingUserDetailInfo()
					})
					
					this.loading = false
				}).catch(err => {
					uni.reLaunch({ url: '/pages/common/illegality/illegality' }); // 关闭所有页面，跳转到对应路径的页面
				})
			},
			// 获取指定时分秒
			getSpecificTimeToday(hours, minutes, seconds) {
			    var today = new Date();
			    today.setHours(hours);
			    today.setMinutes(minutes);
			    today.setSeconds(seconds);
			    return today;
			},
			// 变更当前标签页
			change(e) {
				this.currentTab = e.index
				
				// 在切换后检查并初始化二维码
				if (this.currentTab === 0) {
					this.$nextTick(() => {
						if (this.navbar[this.currentTab]?.ddine_button_show && this.navbar[this.currentTab]?.day_ddine) {
							this.initQrCode();
						}
					});
				}
			},
			// 加/减餐
			changeCurrentTabNumber(e) {
				this.navbar[this.currentTab].num = e.value
			},
			// 退/订餐
			numberOrder(e) {
				this.showActionSheet = true
				this.itemList.type = e
			},
			// 确定操作菜单时间
			itemClick() {
				this.closeActionSheet()
				this.submit_loading = true
				if (this.navbar[this.currentTab].num <= 0) {
					this.submit_loading = false
					this.$refs.toast && this.$refs.toast.show({
						title: '不允许0份',
						imgUrl: "/static/images/toast/info-circle.png",
						icon: true
					});
					return
				}
				const users = uni.getStorageSync(setting.userInfo)
				if (this.itemList.type === 'cancelOrder') {
					this.navbar[this.currentTab].num = 0
				}
				const submitData = {
					userId: users.userid,
					name: users.name,
					mobile: uni.getStorageSync(setting.userDetailInfo).mobile,
					ddineNum: this.navbar[this.currentTab].num,
					ddineDate: this.navbar[this.currentTab].date
				}
				ddineMeal(submitData).then(res => {
					if (this.itemList.type === 'cancelOrder') {
						var typeName = '退餐成功'
					} else {
						var typeName = '订餐成功'
					}
					this.getApiData()
					this.closeActionSheet()
					this.submit_loading = false
					this.$refs.toast && this.$refs.toast.show({
						title: typeName,
						imgUrl: "/static/images/toast/check-circle.png",
						icon: true
					});
				}).catch(err => {
					var typeName = '系统错误'
					if (this.itemList.type === 'cancelOrder') {
						var typeName = '系统错误'
					}
					this.submit_loading = false
					this.$refs.toast && this.$refs.toast.show({
						title: typeName,
						imgUrl: "/static/images/toast/fail-circle.png",
						icon: true
					});
				})
			},
			// 关闭操作菜单事件
			closeActionSheet() {
				this.showActionSheet = false
			},
			// 悬浮按钮
			btnClick(v) {
				if (this.btnList[v.index].text === '刷新') {
					this.submit_loading = true
					this.getApiData()
					this.submit_loading = false
					this.$refs.toast && this.$refs.toast.show({
						title: '刷新成功',
						imgUrl: "/static/images/toast/check-circle.png",
						icon: true
					});
					return
				}
				uni.navigateTo({
					url: this.btnList[v.index].pages
				})
			}
			
		}
	}
</script>

<style lang="scss">
	
	page {
	    background-color: rgb(255, 255, 255);
	}
	
	.my-canvas {
		text-align: center;
		margin: 20px 0px 10px 0px;
	}
	
	.footer_note_class {
		text-align: center;
		color: dimgray;
		font-size: 15px;
	}
	
	.tui-grid-label {
		display: block;
		text-align: center;
		font-weight: 400;
		color: #333;
		font-size: 28rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		margin-top: 10rpx;
	}
	
	.tui-date {
		display: block;
		text-align: center;
		color: rgb(88, 108, 148);
		font-size: 14px;
		font-weight: normal;
		background-color: transparent;
		margin: 30rpx;
	}
	
	.tui-ddine-date {
		display: block;
		text-align: center;
		color: rgb(86, 119, 252);
		font-size: 28px;
		font-weight: bold;
		background-color: transparent;
		margin: 80px 0px 30px 0px;
	}
	
	.tui-number {
		text-align: center;
	}
	
	.tui-btn-box {
		    position: absolute;
		    top: 60px;
		    left: 50%;
		    transform: translate(-50%, -50%);
		    position: relative;
		    width: 90%;
		    margin-bottom: 0.26rem;
	}
</style>
